package com.xiaolin.sports.core.wechat.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiaolin.sports.common.Configuration;
import com.xiaolin.sports.common.QiniuConst;
import com.xiaolin.sports.common.RspResult;
import com.xiaolin.sports.common.enums.OrderStatus;
import com.xiaolin.sports.common.enums.RefundStatus;
import com.xiaolin.sports.common.enums.ResultCode;
import com.xiaolin.sports.common.enums.Status;
import com.xiaolin.sports.common.enums.wechat.WechatEwmType;
import com.xiaolin.sports.controller.BaseController;
import com.xiaolin.sports.model.AuditReqVO;
import com.xiaolin.sports.model.MyPutRet;
import com.xiaolin.sports.model.ProductOrder;
import com.xiaolin.sports.model.ProductRefundOrder;
import com.xiaolin.sports.model.SchoolInfo;
import com.xiaolin.sports.pay.wepay.WXPay;
import com.xiaolin.sports.pay.wepay.common.Configure;
import com.xiaolin.sports.pay.wepay.protocol.refundProtocol.RefundReqData;
import com.xiaolin.sports.pay.wepay.protocol.refundProtocol.RefundResData;
import com.xiaolin.sports.service.IProductOrderService;
import com.xiaolin.sports.service.IProductRefundOrderService;
import com.xiaolin.sports.service.ISchoolInfoService;
import com.xiaolin.sports.utils.AmountArithUtil;
import com.xiaolin.sports.utils.ImageUtil;
import com.xiaolin.sports.utils.QRCoderUtils;
import com.xiaolin.sports.utils.QiniuUtil;
import com.xiaolin.sports.utils.StringUtil;
import com.xiaolin.sports.view.CourseSignOrderView;
import com.xiaolin.sports.vo.ImageSynthesisVo;
import com.xiaolin.sports.wechat.model.WechatQrcodeRsp;
import com.xiaolin.sports.wechat.utils.MessageUtil;
import com.xiaolin.sports.wechat.utils.TemplateUtil;
import com.xiaolin.sports.wechat.utils.WechatUtils;

@RequestMapping("wechatmsg")
@Controller
public class WechatMsgController extends BaseController{
	
	private static Logger logger = LoggerFactory.getLogger(WechatMsgController.class);
	@Autowired
	private IProductOrderService productOrderService;
	@Autowired
	private IProductRefundOrderService productRefundOrderService;
	
	/**
	 * 订单退款
	 * @auther 胡启萌
	 * @Date 2017年4月17日
	 * @param vo
	 * @return
	 */
	@RequestMapping(value="orderRefundMsg", method = RequestMethod.POST)  
    @ResponseBody Object orderRefund(@RequestBody AuditReqVO vo) { 
		try {
			if(vo != null) {
				ProductOrder productOrder = productOrderService.selectById(Integer.valueOf(vo.getIds()));
				if(productOrder != null) {
					ProductRefundOrder refundOrder = new ProductRefundOrder();
					refundOrder.setOutRefundNo(StringUtil.getCourseOrderNum(productOrder.getCustId()));
	        		refundOrder.setOutTradeNo(productOrder.getOrderNo());
	        		refundOrder.setTransNo(productOrder.getTransNo());
	        		refundOrder.setTotalFee(productOrder.getTotalAmount());
	        		refundOrder.setRefundFee(productOrder.getPayAmount());
	        		refundOrder.setOrderStatus(RefundStatus.HANDING.getCode());
	        		refundOrder.setRefundSubmitTime(new Date());
	        		productRefundOrderService.insertSelective(refundOrder);
					RefundReqData reqData = new RefundReqData(
							refundOrder.getTransNo(), 
							refundOrder.getOutTradeNo(), 
							Configure.DEVICE_INFO, 
							refundOrder.getOutRefundNo(), 
							AmountArithUtil.muiFloor(refundOrder.getTotalFee(), 100), 
							AmountArithUtil.muiFloor(refundOrder.getRefundFee(), 100));
					
					RefundResData resData = WXPay.requestRefundService(reqData);
					
					refundOrder.setRefundCallbackTime(new Date());
					refundOrder.setReturnCode(resData.getResult_code());
					if(resData.getReturn_code().equals(ResultCode.SUCCESS.getCode())) {
			        	if(resData.getResult_code().equals(ResultCode.SUCCESS.getCode())) {
			        		refundOrder.setRefundNo(resData.getRefund_id());
			        	}else {
			        		refundOrder.setErrCode(resData.getErr_code());
			        		refundOrder.setErrorReason(resData.getErr_code_des());
			        		refundOrder.setOrderStatus(RefundStatus.FAIL.getCode());
						}
			        }else {
		        		refundOrder.setReturnMsg(resData.getReturn_msg());
		        		refundOrder.setOrderStatus(RefundStatus.FAIL.getCode());
			        }
					productRefundOrderService.updateByPrimaryKeySelective(refundOrder);
					if(refundOrder.getOrderStatus().equals(RefundStatus.HANDING.getCode())) {
						ProductOrder order = productOrderService.selectByOrderNo(refundOrder.getOutTradeNo());
						order.setOrderStatus(OrderStatus.REFUND_HANDING.getCode());
						order.setUpdateTime(new Date());
						productOrderService.updateById(order);
						//退款通知模板
						TemplateUtil.orderRefundApplyMsg(order.getOrderNo(), order.getOpenid(), refundOrder.getRefundFee());
					}
					return new RspResult(Status.SUCCESS, resData);
				}
			}
		} catch (Exception e) {
			logger.error("--orderRefund, error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	/**
	 * 订单支付成功提醒
	 * @auther 胡启萌
	 * @Date 2017年4月17日
	 * @param vo
	 * @return
	 */
	@RequestMapping(value="paySucessMsg", method = RequestMethod.POST)
	@ResponseBody Object paySucessMsg(@RequestBody CourseSignOrderView vo) {
		try {
			CourseSignOrderView view = productOrderService.selectCourseSignOrderByOrderId(vo.getOrderId());
			if(view != null) {
				TemplateUtil.courseOrderPaySucessMsg(vo.getPaySubmitTime(), vo.getOrderNo(), 
						vo.getOpenid(), vo.getSignName(), vo.getCourseName(), vo.getPayAmount());
			}
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("--paySucessMsg, error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping(value="schoolPoster", method = RequestMethod.POST)
	@ResponseBody Object schoolPosterMsg(@RequestBody SchoolInfo record) {
		try {
			List<ImageSynthesisVo> list = new ArrayList<>();
			
			WechatQrcodeRsp rsp = new WechatQrcodeRsp();
			try {
				rsp = WechatUtils.getQrcode(MessageUtil.QR_LIMIT_SCENE, 
						WechatEwmType.POSTER.getCode(), String.valueOf(record.getId()));
			} catch (Exception e) {
				e.printStackTrace();
			}
			ImageSynthesisVo vo1 = new ImageSynthesisVo("image", rsp.getQrcode(), 10, 660, 180, 180);
			ImageSynthesisVo vo2 = new ImageSynthesisVo("text", record.getSchoolName(), 245, 708, 15);
			ImageSynthesisVo vo3 = new ImageSynthesisVo("text", record.getSchoolAddr(), 270, 748, 15);
			list.add(vo1);
			list.add(vo2);
			list.add(vo3);
			String tempPath = this.getClass().getClassLoader().getResource("/").getPath();
        	tempPath = tempPath.replace("/WEB-INF/classes", "");
			String fileSrc = tempPath + "images/zs-poster.jpg";
			String outSrcName = WechatEwmType.POSTER.getCode() + String.valueOf(record.getId()) + ".jpg";
			String outSrc = QRCoderUtils.getPosterRealImgUrl() + File.separator + outSrcName;
			logger.info("----------school poster={}", outSrc);
			ImageUtil.composePic(fileSrc, outSrc, list, null, null);
			MyPutRet putRet = QiniuUtil.fileUpload(outSrc, Configuration.getInstance().getQiniuBucket(), false);
			record.setSchoolEwm(putRet.key);
			return new RspResult(Status.SUCCESS, putRet);
		} catch (Exception e) {
			logger.error("--schoolPosterMsg, error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
}
